package net.chrisrichardson.ec2deployer.cluster

import org.apache.commons.logging.*
import net.chrisrichardson.ec2deployer.applications.ApacheServer
import net.chrisrichardson.ec2deployer.core.CloudManager
import net.chrisrichardson.ec2deployer.core.EC2Server

class WebServerTier extends AbstractTier {

    def Log logger = LogFactory.getLog(getClass())

    ClusterSpec spec

    ApacheServer apacheServer
    AppServerTier appServerTier

    protected WebServerTier() {}

    WebServerTier(CloudManager ec2, spec, appServerTier) {
        super(ec2)
        this.spec = spec
        this.appServerTier = appServerTier
    }

    def saveState(result) {
        result.put("apacheServer", [apacheServer.host.instanceId])
    }

    def restoreState(serverState) {
        this.apacheServer = restoreApacheServer(serverState["apacheServer"])

    }

    def restoreApacheServer(previousInstanceId) {
        if (previousInstanceId)
            return new ApacheServer(ec2.findInstance(previousInstanceId[0]), appServerTier, spec)
    }

    def assignHosts(hosts) {
        apacheServer = new ApacheServer(hosts.apacheServer, appServerTier, spec)
    }

    void performStart() {
        phase("Configuring apache") {
            apacheServer.configure()
        }
    }

    void assignIpAddress() {
        if (spec.externalIpAddress) {
            apacheServer.host.associateAddress spec.externalIpAddress
        }
    }

    List<EC2Server> getServers() {
        apacheServer ? [apacheServer.host] : []
    }

    def getPrivateDnsName() {
        apacheServer.hostPrivateDnsName
    }

    def getPort() {
        apacheServer.port
    }

    def getSarMonitor() {
        apacheServer.sarMonitor
    }

    void curl(String path, String method) {
        apacheServer.curl(path, method)
    }
 }

